package com.farm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.farm.entity.Cart;
import com.farm.entity.Product;
import com.farm.mapper.CartMapper;
import com.farm.service.CartService;
import com.farm.service.ProductService;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private ProductService productService;

    @Override
    @Transactional
    public void addToCart(Long employeeId, Long productId, Integer quantity) {
        // 检查商品是否存在
        Product product = productService.getProductById(productId);
        if (product == null || product.getStatus() != 1) {
            throw new RuntimeException("商品不存在或未上架");
        }

        // 检查库存
        if (product.getStock() < quantity) {
            throw new RuntimeException("商品库存不足");
        }

        // 检查购物车是否已存在该商品
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("employee_id", employeeId)
               .eq("product_id", productId);
        Cart existingCart = cartMapper.selectOne(wrapper);

        if (existingCart != null) {
            // 更新数量
            existingCart.setQuantity(existingCart.getQuantity() + quantity);
            cartMapper.updateById(existingCart);
        } else {
            // 新增购物车项
            Cart cart = new Cart();
            cart.setEmployeeId(employeeId);
            cart.setProductId(productId);
            cart.setQuantity(quantity);
            cart.setPrice(product.getPrice());
            cartMapper.insert(cart);
        }
    }

    @Override
    @Transactional
    public void updateQuantity(Long cartId, Integer quantity) {
        Cart cart = cartMapper.selectById(cartId);
        if (cart == null) {
            throw new RuntimeException("购物车项不存在");
        }

        // 检查库存
        Product product = productService.getProductById(cart.getProductId());
        if (product.getStock() < quantity) {
            throw new RuntimeException("商品库存不足");
        }

        cart.setQuantity(quantity);
        cartMapper.updateById(cart);
    }

    @Override
    @Transactional
    public void removeFromCart(Long cartId) {
        cartMapper.deleteById(cartId);
    }

    @Override
    public List<Cart> getUserCart(Long employeeId) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("employee_id", employeeId);
        return cartMapper.selectList(wrapper);
    }

    @Override
    @Transactional
    public void clearUserCart(Long employeeId) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("employee_id", employeeId);
        cartMapper.delete(wrapper);
    }
} 